/**
 * 
 */
package org.tio.sitexxx.web.server.utils;

import java.awt.image.BufferedImage;
import java.io.File;

import org.tio.sitexxx.service.model.main.Img;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ImageUtil;

/**
 * @author tanyaowu
 *
 */
public class ImgUtils {

	/**
	 * 
	 */
	public ImgUtils() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

	}

	/**
	 * 用目标宽度计算缩放比
	 * @param maxWidth
	 * @param initBufferedImage
	 * @return
	 */
	public static float calcScaleWithWidth(int maxWidth, BufferedImage initBufferedImage) {
		int initWidth = initBufferedImage.getWidth();
		int newWidth = Math.min(maxWidth, initWidth);
		return (float) newWidth / (float) initWidth;
	}

	/**
	 * 用目标高度计算缩放比
	 * @param maxHeight
	 * @param initBufferedImage
	 * @return
	 */
	public static float calcScaleWithHeight(int maxHeight, BufferedImage initBufferedImage) {
		int initHeight = initBufferedImage.getHeight();
		int newHeight = Math.min(maxHeight, initHeight);
		return (float) newHeight / (float) initHeight;
	}

	public static Img processImg(BufferedImage initBufferedImage, String imgFilePath, String smImgFilePath, float scale) throws Exception {

		File imgFile = new File(imgFilePath);
		File smImgFile = new File(smImgFilePath);

		ImageUtil.scale(imgFile, smImgFile, scale);

		BufferedImage smBi = ImageUtil.read(smImgFile);

		Img img = new Img();
		img.setCoverheight(smBi.getHeight());
		img.setCoversize((int) FileUtil.size(smImgFile));
		img.setCoverwidth(smBi.getWidth());

		String filename = FileUtil.getName(imgFile);
		img.setFilename(filename);
		img.setHeight(initBufferedImage.getHeight());
		img.setWidth(initBufferedImage.getWidth());
		img.setSize(FileUtil.size(imgFile));

		img.setTitle(filename);

		return img;

	}

}
